import store from '@/store'

/**
 * 获取感受列表
 * @param {Object} params - 查询参数
 * @returns {Promise}
 */
export function getFeelList(params = { current: 1, size: 100 }) {
  return store.dispatch('feel/getFeelList', params)
}

/**
 * 新增感受
 * @param {Object} data - 感受数据
 * @returns {Promise}
 */
export function addFeel(data) {
  return store.dispatch('feel/addFeel', data)
}

/**
 * 修改感受
 * @param {Object} data - 感受数据
 * @returns {Promise}
 */
export function editFeel(data) {
  return store.dispatch('feel/editFeel', data)
}

/**
 * 删除感受
 * @param {Number|Array} ids - 感受ID或ID数组
 * @returns {Promise}
 */
export function deleteFeel(ids) {
  return store.dispatch('feel/deleteFeel', ids)
}

/**
 * 刷新感受列表
 * @returns {Promise}
 */
export function refreshFeelList() {
  return store.dispatch('feel/refreshFeelList')
}

/**
 * 根据ID获取感受名称
 * @param {Number} id - 感受ID
 * @returns {String}
 */
export function getFeelNameById(id) {
  return store.getters['feel/getFeelNameById'](id)
}

/**
 * 根据ID获取感受对象
 * @param {Number} id - 感受ID
 * @returns {Object}
 */
export function getFeelById(id) {
  return store.getters['feel/getFeelById'](id)
}

/**
 * 获取感受列表（从 store 中获取，不发起请求）
 * @returns {Array}
 */
export function getFeelListFromStore() {
  return store.getters['feel/feelList']
}

/**
 * 检查感受数据是否已加载
 * @returns {boolean} 是否已加载
 */
export function isFeelDataLoaded() {
  return store.getters['feel/feelList'].length > 0
}

/**
 * 确保感受数据已加载
 * @returns {Promise} 加载Promise
 */
export async function ensureFeelDataLoaded() {
  if (!isFeelDataLoaded()) {
    await store.dispatch('feel/getFeelList')
  }
  return store.getters['feel/feelList']
}

/**
 * 获取感受选项用于下拉选择
 * @returns {Array} 选项数组，格式为 [{value: id, label: name}]
 */
export function getFeelOptions() {
  const feelList = store.getters['feel/feelList']
  return feelList.map(feel => ({
    value: feel.id,
    label: feel.name
  }))
}

/**
 * 将感受ID字符串转换为感受名称
 * @param {string} feelIds - 感受ID字符串，格式如 "1,2,3"
 * @param {string} separator - 分隔符，默认为 ","
 * @returns {string} 感受名称字符串
 */
export function convertFeelIdsToNames(feelIds, separator = ',') {
  if (!feelIds) return ''
  
  const ids = feelIds.split(separator).map(id => id.trim()).filter(id => id)
  const names = ids.map(id => {
    const feel = store.getters['feel/getFeelById'](parseInt(id))
    return feel ? feel.name : `未知感受(${id})`
  })
  
  return names.join(separator)
}

/**
 * 将感受ID字符串转换为感受对象数组
 * @param {string} feelIds - 感受ID字符串，格式如 "1,2,3"
 * @param {string} separator - 分隔符，默认为 ","
 * @returns {Array} 感受对象数组
 */
export function convertFeelIdsToObjects(feelIds, separator = ',') {
  if (!feelIds) return []
  
  const ids = feelIds.split(separator).map(id => id.trim()).filter(id => id)
  return ids.map(id => {
    const feel = store.getters['feel/getFeelById'](parseInt(id))
    return feel || { id: parseInt(id), name: `未知感受(${id})` }
  })
}

/**
 * 将感受对象数组转换为ID字符串
 * @param {Array} feels - 感受对象数组
 * @param {string} separator - 分隔符，默认为 ","
 * @returns {string} 感受ID字符串
 */
export function convertFeelsToIds(feels, separator = ',') {
  if (!feels || !Array.isArray(feels)) return ''
  
  const ids = feels.map(feel => feel.id || feel).filter(id => id)
  return ids.join(separator)
}

/**
 * 解析感受ID字符串为数字数组
 * @param {string} feelIds - 感受ID字符串，格式如 "1,2,3"
 * @param {string} separator - 分隔符，默认为 ","
 * @returns {Array} 数字ID数组
 */
export function parseFeelIds(feelIds, separator = ',') {
  if (!feelIds) return []
  
  return feelIds.split(separator)
    .map(id => id.trim())
    .filter(id => id)
    .map(id => parseInt(id))
    .filter(id => !isNaN(id))
}

/**
 * 格式化感受显示，支持HTML标签
 * @param {string} feelIds - 感受ID字符串
 * @param {string} separator - 分隔符，默认为 ","
 * @param {boolean} useHtml - 是否使用HTML格式，默认为false
 * @returns {string} 格式化后的感受名称
 */
export function formatFeelDisplay(feelIds, separator = ',', useHtml = false) {
  if (!feelIds) return ''
  
  const ids = parseFeelIds(feelIds, separator)
  const names = ids.map(id => {
    const feel = store.getters['feel/getFeelById'](id)
    return feel ? feel.name : `未知感受(${id})`
  })
  
  if (useHtml) {
    return names.map(name => `<span class="feel-tag">${name}</span>`).join(' ')
  }
  
  return names.join(separator)
}

// 向后兼容的方法
export const ensureFeelListLoaded = ensureFeelDataLoaded
export const isFeelListLoaded = isFeelDataLoaded

/**
 * 将感受字符串转换为名称字符串（旧格式：id1|id2|...|其他症状）
 * @param {String} feelsString - 感受字符串，格式：id1|id2|...|其他症状
 * @returns {String} 感受名称字符串
 */
export function convertFeelsToString(feelsString) {
  if (!feelsString) {
    return '无'
  }
  
  const parts = feelsString.split('|')
  if (parts.length <= 1) {
    return feelsString || '无'
  }
  
  // 前N-1个部分是感受ID，最后一个是其他症状
  const feelIds = parts.slice(0, -1)
  const otherFeel = parts[parts.length - 1]
  
  const feelNames = feelIds
    .map(id => {
      const numId = parseInt(id)
      const feel = store.getters['feel/getFeelById'](numId)
      return !isNaN(numId) && feel ? feel.name : id
    })
    .filter(name => name) // 过滤掉空值
  
  if (feelNames.length === 0) {
    return otherFeel || '无'
  }
  
  return feelNames.join('、') + (otherFeel ? `<br/>其他：${otherFeel}` : '')
}

/**
 * 解析感受字符串（旧格式：id1|id2|...|其他症状）
 * @param {String} feelsString - 感受字符串
 * @returns {Object} { selectedIds: [], otherFeel: '' }
 */
export function parseFeelsString(feelsString) {
  if (!feelsString) {
    return { selectedIds: [], otherFeel: '' }
  }
  
  const parts = feelsString.split('|')
  if (parts.length <= 1) {
    return { selectedIds: [], otherFeel: feelsString }
  }
  
  const selectedIds = parts.slice(0, -1).map(id => parseInt(id)).filter(id => !isNaN(id))
  const otherFeel = parts[parts.length - 1] || ''
  
  return { selectedIds, otherFeel }
}

/**
 * 构建感受字符串（旧格式：id1|id2|...|其他症状）
 * @param {Array} selectedIds - 选中的感受ID数组
 * @param {String} otherFeel - 其他症状
 * @returns {String} 感受字符串
 */
export function buildFeelsString(selectedIds, otherFeel = '') {
  const ids = selectedIds || []
  const other = otherFeel || ''
  return [...ids, other].join('|')
} 